package com.chen.controller;

import com.alibaba.fastjson.JSON;
import com.chen.User;
import com.chen.entity.Pager;
import com.chen.entity.Spinguser;
import com.chen.exception.UserException;
import com.chen.service.SpinguserService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/14.
 */

@Controller
@RequestMapping("/user")
public class SpingUserController {
    private Map<String, Spinguser> users = new HashMap<String, Spinguser>();
    @Autowired
    SpinguserService spinguserService;
//
//    @RequestMapping(value = "/list", method = RequestMethod.GET)
//    public String seletAll(Model model) {
//
//        List<Spinguser> spinguserList = spinguserService.selectAll();
//        model.addAttribute(spinguserList);
//        return "user/list";
//    }


    //    分页查看所有学生信息
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String showList(HttpServletRequest request, Model model) {

        int page = 0;

        if (request.getParameter("pager.offset") != null) {
            page = Integer.parseInt(request.getParameter("pager.offset"));
        }

        Pager<Spinguser> userPager = new Pager<>();
//        设置总页数
        int allPages;

        if (spinguserService.allPages() % userPager.getPageSize() == 0) {
            allPages = spinguserService.allPages() / userPager.getPageSize();
            System.out.println(allPages + "-----");
        } else {
            allPages = spinguserService.allPages() / userPager.getPageSize() + 1;
            System.out.println(allPages+"*****");
        }
        userPager.setTotalPage(allPages);
//        总记录
        userPager.setTotalRecord(spinguserService.allPages());
//        设置当前页
        int thisPage = (page + userPager.getPageSize()) / userPager.getPageSize();

        userPager.setPageIndex(thisPage);


        List<User> spinguserList = spinguserService.selectSpinguserByPage(page, userPager.getPageSize());
        model.addAttribute("pager", userPager);
        model.addAttribute("spinguserList", spinguserList);
        return "user/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
//    new 新用户    开启modelDriven
        Spinguser spinguser = new Spinguser();
        model.addAttribute(spinguser);
        return "user/add";

    }


    //    在具体添加用户时是post请求，就访问下面代码，文件添加
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@Validated Spinguser spinguser, BindingResult br, @RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) throws IOException {
        if (br.hasErrors()) {
            return "user/add";
        }
        String realpath = req.getSession().getServletContext().getRealPath("/resources/upload");
        System.out.println(realpath);
        for (MultipartFile attach : attachs) {
            if (attach.isEmpty()) continue;
            File f = new File(realpath + "/" + attach.getOriginalFilename());
            FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
            System.out.println(attach.getName() + "," + attach.getOriginalFilename() + "," + attach.getContentType());
        }
        spinguserService.insertData(spinguser);
//        users.put(spinguser.getUsername(), spinguser);
        return "redirect:/user/list";//客户端跳转


    }

    //    查看详情页面
    @RequestMapping(value = "/{username}", method = RequestMethod.GET)
    public String show(@PathVariable String username, Model model) {


        Spinguser spinguser = spinguserService.selectByName(username);
//        System.out.println("--------------------------" + JSON.toJSON(spinguser).toString());

        model.addAttribute("username", spinguser);

        return "user/show";
    }

    ////修改用户信息
    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable int id, Model model,HttpServletRequest request) {

        Spinguser spinguser = new Spinguser();

        spinguser.setId(id);

//        Spinguser spinguser1=spinguserService.selectByPrimaryKey(id);


        model.addAttribute(spinguser);
        return "user/update";
    }

    //    修改信息
    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String update(@PathVariable int id, @Validated Spinguser spinguser, BindingResult br, Model model) {
        if (br.hasErrors()){
            return "user/update";
        }
//        Spinguser spinguser1 =spinguserService.selectByPrimaryKey(id);
        System.out.println(spinguser.getId()+"-------"+id);
        spinguserService.updateByPrimaryKey(spinguser);
//        model.addAttribute("spinguserList",spinguser1);
//


//        users.put(id, spinguser);
        return "redirect:/user/list";
    }


    //删除信息
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable int id) {
        spinguserService.deleteByPrimaryKey(id);
        return "redirect:/user/list";
    }

//登录页面
        @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(Model model) {
        model.addAttribute("users", users);

        return "user/login";

    }
    //登录和验证
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String username,String password,HttpSession session,Model model){
        System.out.println(username + password + "------------------------------------");



        Spinguser spinguser = spinguserService.selectByName(username);

        String userPassword=spinguser .getPassword();


        System.out.println(userPassword);
        if (!password.equals(userPassword)){
            throw new UserException("用户名或者密码不存在");
        }



        session.setAttribute("loginUser", spinguser);
        return "redirect:/user/list";
    }
    ////    局部异常处理
    @ExceptionHandler(value = {UserException.class})
    public String handlerException(UserException e,HttpServletRequest req){
        req.setAttribute("e", e);
        return "user/error";

    }
    @RequestMapping(value = "/zhuce", method = RequestMethod.GET)
    public String zhuce(Model model) {
//    new 新用户    开启modelDriven
        Spinguser spinguser = new Spinguser();
        model.addAttribute(spinguser);
        return "user/zhuce";

    }


    //    在具体添加用户时是post请求，就访问下面代码，文件添加
    @RequestMapping(value = "/zhuce", method = RequestMethod.POST)
    public String zhuce(@Validated Spinguser spinguser, BindingResult br, @RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) throws IOException {
        if (br.hasErrors()) {
            return "user/add";
        }
        String realpath = req.getSession().getServletContext().getRealPath("/resources/upload");
        System.out.println(realpath);
        for (MultipartFile attach : attachs) {
            if (attach.isEmpty()) continue;
            File f = new File(realpath + "/" + attach.getOriginalFilename());
            FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
            System.out.println(attach.getName() + "," + attach.getOriginalFilename() + "," + attach.getContentType());
        }
        spinguserService.insertData(spinguser);
//        users.put(spinguser.getUsername(), spinguser);
        return "redirect:/user/list";//客户端跳转


    }
}
